import httpx
from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
import uvicorn

app = FastAPI()

# 目标视频流URL（RTSP或HTTP流）
STREAM_URL = "https://112.23.26.254:8443/streamer/stream?key=sYvLOJn56Lo5ZCMD&advance_headers=1"

cookies = {
    "auth_token":
    "7e6dc3de202f02b0d66c2f3647119a9aa4f71aecdf60ee012c911c441e468fff",
    "stream_client": "sYvLOJn56Lo5ZCMD/ed98448e9612671"
}


@app.get("/stream")
async def stream_video():
    try:
        async with httpx.AsyncClient(cookies=cookies,
                                     timeout=None,
                                     verify=False) as client:
            async with client.stream("GET", STREAM_URL) as response:
                # 检查响应状态码
                if response.status_code != 200:
                    raise HTTPException(status_code=response.status_code,
                                        detail="视频流获取失败")

                # 获取响应头，透传部分关键头信息
                headers = {
                    "Content-Type":
                    response.headers.get("Content-Type", "video/mp4"),
                }

                # 流式返回视频内容
                return StreamingResponse(response.aiter_raw(),
                                         headers=headers,
                                         media_type="video/mp4")
    except httpx.RequestError as e:
        raise HTTPException(status_code=502, detail=f"视频流请求失败: {str(e)}")
    except httpx.StreamClosed:
        raise HTTPException(status_code=502, detail="视频流提前关闭")


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
